import asyncio
import base64
import functools
import hashlib
import json as jsonlib
import os
import time

import aiohttp
import matplotlib
import redis as redislib
from aiohttp import web
from PIL import Image


async def index(request):
    return web.Response(text='hello world!', content_type='text/html')


async def savePicture(request):

    data = await content2data(request.content)

    # 计算图片哈希值
    hashsss = hashlib.md5()
    hashsss.update(data['picture'].encode("utf8"))
    uuid = hashsss.hexdigest()

    # 设置图片唯一标识，以便返回前端轮询
    data['uuid'] = uuid

    # 保存 Redis
    redis.lpush('picture', jsonlib.dumps(data))

    # 保存图片
    picture = base64.b64decode(data['picture'])
    file = open('tmp.bmp', 'wb')
    file.write(picture)
    file.close()

    im = Image.open('tmp.bmp')
    im.show()
    im.close()
    del data['picture']
    return JsonResponse(data)


async def content2data(content):
    data = await content.readany()
    return jsonlib.loads(data.decode())


async def getPicture(request):

    data = await content2data(request.content)
    picture = redis.get(data['uuid'])
    data['picture'] = picture
    return JsonResponse(data)


async def init(loop):

    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', index)
    app.router.add_route('POST', '/getPicture', getPicture)
    app.router.add_route('POST', '/savePicture', savePicture)
    srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
    print('Server started at http://127.0.0.1:8000...')
    return srv


# JSON 响应
def JsonResponse(text):
    if isinstance(text, str) == False:
        text = jsonlib.dumps(text)
    return web.Response(text=text, content_type='application/json')


redis = redislib.Redis(host='127.0.0.1', port=6379, db=0)
print(redis.get("lover"))

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
